<?php

require_once('conf/DBConnection.php');
require_once('dao/DAO.php');

class ClientesDAO extends DAO {

	function ClientesDAO() {}


	function get($id){
		DBConnection::getInstance();
		$query = "SELECT * FROM clientes WHERE id = $id";
		$result = mysql_query($query);
		$results = $this->getFromResult($result);
		return $results[0];
	}

	function find($criteria){
		DBConnection::getInstance();
		$conditions = $this->getConditions($criteria);
		$query = "SELECT * FROM clientes WHERE 1=1 $conditions";
		//echo $query;
		$result = mysql_query($query);
		return $this->getFromResult($result);
	}

	function deleteFisico($id){
		DBConnection::getInstance();
		$query = "DELETE FROM clientes WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function delete($id){
		DBConnection::getInstance();
		$query = "UPDATE clientes SET borrado = '1' WHERE id = $id";
		$result = mysql_query($query);
		return parent::checkError($result);
	}

	function insert($vo) {
		DBConnection::getInstance();
		$query = "INSERT INTO clientes(id, comitente, nombre, direccion, telefono, celular, mail, borrado) VALUES
(NULL, '".$vo->getComitente()."', '".$vo->getNombre()."', '".$vo->getDireccion()."', '".$vo->getTelefono()."', '".$vo->getCelular()."', '".$vo->getMail()."', '".$vo->getBorrado()."')";
		$result = mysql_query($query);
		$id = null;
		if ($result){
			$id = mysql_insert_id();
		}
		return $id;
	}

	function update($vo) {
		DBConnection::getInstance();
		$query = "UPDATE clientes SET ".
				"comitente ='".$vo->getComitente()."', ".
				"nombre ='".$vo->getNombre()."', ".
				"direccion ='".$vo->getDireccion()."', ".
				"telefono ='".$vo->getTelefono()."', ".
				"celular ='".$vo->getCelular()."', ".
				"mail ='".$vo->getMail()."'".
				" WHERE id =".$vo->getId();
		$result = mysql_query($query);
		//echo $query;
		return parent::checkError($result);
	}

	function getConditions($criteria){
		if ($criteria->getId() != null) {
			$conditions.= " AND id= '".$criteria->getId()."'";
		}
		if ($criteria->getComitente() != null) {
			$conditions.= " AND comitente= '".$criteria->getComitente()."'";
		}
		if ($criteria->getNombre() != null) {
			$conditions.= " AND nombre= '".$criteria->getNombre()."'";
		}
		if ($criteria->getSearch() != null) {
			$conditions.= " AND nombre like '%".$criteria->getSearch()."%' OR comitente= '".$criteria->getSearch()."'";
		}
		$conditions .= parent::getConditionsAbs($criteria,'clientes');
		return $conditions;
	}

}


